package common;

import io.github.bonigarcia.wdm.managers.ChromeDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class AutoTestUtil {
    public static ChromeDriver driver;
    private WebDriver createDriver(){
        //创建驱动
        if(driver == null){
            ChromeDriverManager.chromedriver().setup();

            //设置前置条件
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");
            //创建驱动对象
            driver = new ChromeDriver(options);

            //设置隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }
    //设置构造函数
    public AutoTestUtil(){
        createDriver();
    }
    //设置截图操作
    public void getScreen(String str) throws IOException {
        //格式操作
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");
        //获取时间操作
        String dirName = sim1.format(System.currentTimeMillis());
        String comName = sim2.format(System.currentTimeMillis());

        //拼接字符串.src/test/image/dirName/str/comName.png
        String fileName = "src/test/image/" + dirName + "/" + str + "/" + comName + ".png";
        //调用截图接口

        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile,new File(fileName));
    }
}
